#!/bin/bash

set -o errexit

test_dir=$(realpath $(dirname $0))
. ${test_dir}/../functions

set_debug

cluster='some-name'

wait_for_sts_generation() {
	local name="${1}"
	local desired_generation="${2}"
	local size="${3}"
	set +o xtrace
	echo -n "Waiting for statefulset readyness"
	retry=0
	until [[ "$(kubectl_bin get sts $name -o jsonpath='{.status.observedGeneration}')" == "${desired_generation}" &&
	"$(kubectl_bin get sts $name -o jsonpath='{.status.readyReplicas}')" -ge ${size} ]]; do
		sleep 1
		echo -n .
		let retry+=1
		if [ $retry -ge 300 ]; then
			kubectl_bin logs $(get_operator_pod) ${OPERATOR_NS:+-n $OPERATOR_NS}
			echo max retry count $retry reached. something went wrong with operator or kubernetes cluster
			exit 1
		fi
	done
	echo
	set -o xtrace
}

main() {
	create_infra $namespace

	apply_config "$conf_dir/client.yml"
	kubectl_bin apply \
		-f "$test_dir/conf/secrets.yml"
	cat_config "$conf_dir/$cluster.yml" \
		| yq eval '.spec.crVersion = "1.10.0"' - \
		| kubectl_bin apply -f -

	desc "test 1.10.0"
	wait_cluster_consistency "$cluster" 3 2
	wait_for_sts_generation "$cluster-pxc" "1" "1"
	desc "compare k8s objects"
	compare_kubectl service/$cluster-pxc "-1100"
	compare_kubectl service/$cluster-proxysql "-1100"
	compare_kubectl statefulset/$cluster-pxc "-1100"
	compare_kubectl statefulset/$cluster-proxysql "-1100"

	desc "test 1.11.0"
	kubectl_bin patch pxc "$cluster" --type=merge --patch '{
        "spec": {"crVersion":"1.11.0"}
    }'
	wait_cluster_consistency "$cluster" 3 2
	wait_for_sts_generation "$cluster-pxc" "2" "1"
	desc "compare k8s objects"
	compare_kubectl service/$cluster-pxc "-1110"
	compare_kubectl service/$cluster-proxysql "-1110"
	compare_kubectl statefulset/$cluster-pxc "-1110"
	compare_kubectl statefulset/$cluster-proxysql "-1110"

	desc "test 1.12.0"
	kubectl_bin patch pxc "$cluster" --type=merge --patch '{
        "spec": {"crVersion":"1.12.0"}
    }'
	wait_cluster_consistency "$cluster" 3 2
	wait_for_sts_generation "$cluster-pxc" "3" "1"
	desc "compare k8s objects"
	compare_kubectl service/$cluster-pxc "-1120"
	compare_kubectl service/$cluster-proxysql "-1120"
	compare_kubectl statefulset/$cluster-pxc "-1120"
	compare_kubectl statefulset/$cluster-proxysql "-1120"

	desc "test 1.13.0"
	kubectl_bin patch pxc "$cluster" --type=merge --patch '{
        "spec": {"crVersion":"1.13.0"}
    }'
	wait_cluster_consistency "$cluster" 3 2
	wait_for_sts_generation "$cluster-pxc" "4" "1"
	desc "compare k8s objects"
	compare_kubectl service/$cluster-pxc "-1130"
	compare_kubectl service/$cluster-proxysql "-1130"
	compare_kubectl statefulset/$cluster-pxc "-1130"
	compare_kubectl statefulset/$cluster-proxysql "-1130"

	destroy "${namespace}"
	desc "test passed"
}

main
